﻿using System.Collections.Generic;
using System.Windows.Threading;

using agsXMPP;
using agsXMPP.protocol.client;

using VSTalk.Tools;

namespace VSTalk.Engine.Core.XmppConnection.PresenceObserver
{
    public class PresenceObserver : IListener
    {
        private XmppClientConnection _connection;

        private List<IPresenceHandler> _handlers = new List<IPresenceHandler>();

        private Dispatcher _dispatcher;
        private IActionWrapper<object, Presence> _onPresence;

        public PresenceObserver(XmppClientConnection connection)
        {
            _dispatcher = Dispatcher.CurrentDispatcher;

            _connection = connection;

        }

        public void AddHandler(IPresenceHandler handler)
        {
            _handlers.Add(handler);
        }
        
        private void OnPresence(object sender, Presence pres)
        {
            foreach (var presenceHandler in _handlers)
            {
                if (presenceHandler.IsApplicable(pres))
                {
                    presenceHandler.UpdateState(pres);
                }
            }
        }

        public void StartListen()
        {
            _onPresence = _dispatcher.Wrap<object, Presence>(OnPresence);
            _connection.OnPresence += _onPresence.Exec;
        }

        public void StopListen()
        {
            _connection.OnPresence -= _onPresence.Exec;
        }
    }
}